﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace DAL_Library
{
    [Serializable()]
    public class RecipesDAL
    {
       
        /// <summary>
        /// Ska ladda/hämta recepten från en fil
        /// </summary>
        public List<object> LoadRecipes()
        {
            try
            {
                var resultList = new List<object>();
                using (Stream stream = File.Open("recipes.bin", FileMode.Open))
                {
                    var bin = new BinaryFormatter();

                    var recipes = (List<object>)bin.Deserialize(stream);

                    resultList.AddRange(recipes); // LINQ-uttryck ekvivalent med en foreach- alt. forloop
                }
                return resultList;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            } 
        }
        
        /// <summary>
        /// Sparar/serialiserar recepten till en fil
        /// </summary>
        /// <param name="a_recipesList">Listan med recept som ska sparas</param>
        public void SaveRecipes(List<object> a_recipesList)
        {
            try
            {
                if (a_recipesList != null)
                {
                    using (Stream stream = File.Open("recipes.bin", FileMode.Create))
                    {
                        var bin = new BinaryFormatter();
                        bin.Serialize(stream, a_recipesList);
                    }
                } 
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            } 
        }
    }
}
